package com.ypinkj.app.api;


import com.ypinkj.app.utils.FtpUtil;
import com.ypinkj.app.utils.document.FtpToPDFUtil;
import com.ypinkj.app.utils.resultutils.Result;
import com.ypinkj.app.utils.resultutils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ypinkj.app.annotation.UserLoginToken;
import com.ypinkj.app.entity.UResumeAttachment;
import com.ypinkj.app.mapper.UserApplyPositionMapper;
import com.ypinkj.app.service.UResumeAttachmentService;
import com.ypinkj.app.service.UserApplyPositionService;
import com.ypinkj.app.utils.resultutils.Result;
import com.ypinkj.app.utils.resultutils.ResultUtil;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * 附件简历
 * 前端控制器
 * </p>
 *
 * @author LF
 * @since 2020-09-29
 */
@Api(tags = "附件简历")
@RestController
@RequestMapping("/u-resume-attachment")
public class UResumeAttachmentController {
    // 上传文件大小的上限值
    @Value("${project.resume.pdf-max-size}")
    private int resumeMaxSize;
    // 允许上传的文件类型
    private static final List<String> RESUME_TYPES = new ArrayList<>();

    //允许上传的格式
    static {
        RESUME_TYPES.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");//.docx
        RESUME_TYPES.add("application/pdf");
        RESUME_TYPES.add("application/msword");//.doc
    }

    @Autowired
    private UResumeAttachmentService uResumeAttachmentService;

    @Autowired
    private UserApplyPositionMapper userApplyPositionMapper;


    //    查询用户的所有简历
    //@UserLoginToken
    @RequestMapping("getUserAttachment/{userId}")
    public Result getUserAttachment(@PathVariable("userId") String userId) {


        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userid", userId);
        List list = uResumeAttachmentService.list(queryWrapper);


        return ResultUtil.success(list);
    }

    //附件简历上传
    @ApiOperation(value = "附件简历上传")
    @PutMapping
    public Result save(MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtil.error("请选择要上传的简历");
        }
        // 检查上传的文件大小
        if (file.getSize() > resumeMaxSize) {
            return ResultUtil.error("不允许上传超过" + resumeMaxSize / 1024 + "KB的文件");
        }
        String fileType = file.getContentType().toLowerCase();//获取文件类型转换为小写****
        if (!RESUME_TYPES.contains(fileType)) {
            return ResultUtil.error("您上传的文件类型超出了限制，允许上传的文件类型有：" + RESUME_TYPES);
        }
        String url = "";
        try {
            url = FtpToPDFUtil.uploadFile(file);
        } catch (Exception e) {
            System.out.println(e);
            return ResultUtil.errorMsg();
        }
        return ResultUtil.success(url);
    }



    private static final String URL_FILE = "C:\\Users\\xiao1993\\Desktop\\app\\";//本地路径
    private static final String LINUX_URL_FILE = "/home/user-file/index/app/";//服务器路径

    //    下载简历
    //@UserLoginToken
    @RequestMapping("/getExcel")
    public void getUserExcel(@RequestParam("fileId") String fielId, @RequestParam("applyPositionId") String applyPositionId, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        FileInputStream fis = null;
        UResumeAttachment uResumeAttachment = uResumeAttachmentService.getById(fielId);
        String rul = uResumeAttachment.getResumeurl();
        String substring = rul.substring(rul.lastIndexOf("app") + 4);

        try {
            File file = new File(URL_FILE + substring);
            fis = new FileInputStream(file);
            response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();
            //修改已经下载
            userApplyPositionMapper.updateApplyPositionId(applyPositionId);


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}